package mvv.learn.spring.anno;

import java.lang.reflect.Method;

import mvv.learn.spring.utilities.AppParam;
import mvv.learn.spring.utilities.ResResponse;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * @author Manh Vu
 */
@Component
public class HelloTheWorldIntercepter implements MethodInterceptor {
	private static final Logger log = LoggerFactory.getLogger(HelloTheWorldIntercepter.class);

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		final String textMethod = invocation.getMethod().toGenericString();
		final StopWatch stopWatch = new StopWatch(textMethod);
		stopWatch.start(textMethod);

		ResResponse res = null;

		try {
			log.debug("--> START METHOD {} ..", textMethod);

			Method method = invocation.getMethod();
			HelloTheWorld annotation = method.getAnnotation(HelloTheWorld.class);

			res = (ResResponse) invocation.proceed();
			res.setData(String.format("%s say: Hello the %s!", annotation.value(), res.getData()));

		}catch (Exception e) {
			log.error(e.getMessage(), e);
			res = new ResResponse(AppParam.V_GOOD, e.getMessage(), e);
		}finally {
			stopWatch.stop();
			log.debug(stopWatch.prettyPrint());
			log.debug("--> END METHOD {} ..", textMethod);
		}

		return res;
	}
}
